package cn.lavender.web.async;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * <p>
 * 异步处理时，线程池配置
 * 配合@EnableAsync注解一起使用，{@link org.springframework.scheduling.annotation.EnableAsync}。@EnableAsync 注解在@SpringBootApplication注解上即可
 *
 * @Async ：原理：底层使用JDK的CompletableFuture
 * </p>
 * @author: zhu.chen
 * @date: 2021/3/22
 * @version: v1.0.0
 */
@EnableAsync
@Configuration
public class AsyncThreadPoolAutoConfigure {

    /**
     * 异步线程池
     */
    private static final String ASYNC_THREAD_POOL = "async-thread-pool-";

    /**
     * CorePoolSize：核心线程数的设置需要依据当前应用到底是CPU密集型的还是IO密集型的。
     * CPU密集型：CPU核数+1
     * IO密集型：CPU核数*2
     */
    @Bean
    public AsyncTaskExecutor asyncThreadPoolExecutor() {
        ThreadPoolTaskExecutor asyncThreadPoolExecutor = new ThreadPoolTaskExecutor();
        asyncThreadPoolExecutor.setCorePoolSize(1);
        asyncThreadPoolExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors());
        asyncThreadPoolExecutor.setThreadNamePrefix(ASYNC_THREAD_POOL);
        return asyncThreadPoolExecutor;
    }

}
